﻿using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Blog.Core.IRepositories.JWT
{
	public class JwtTokenHelper
	{
		private readonly IOptions<JWTTokenOptions> options;
		public JwtTokenHelper(IOptions<JWTTokenOptions> options)
		{
			this.options = options;
		}

		public TokenResult CreateToken<T>(T token) where T : class
		{
			List<Claim> claims = new List<Claim>();
			foreach(var item in token.GetType().GetProperties())
			{
				object obj=item.GetValue(token);
				string value = "";
				if (obj != null)
				{
					value = obj.ToString();
				}

				claims.Add(new Claim(item.Name, value));
			}

			//生成密钥
			var key=new SymmetricSecurityKey(Encoding.UTF8.GetBytes("dhajwhdkajwhdkqajwhdkjawhdkjawhdkjawhdjkawhdakjwhdwajkdhjkwh"));
			//设置令牌的过期时间
			DateTime expires= DateTime.Now.AddSeconds(options.Value.Expire);
			//HS256加密 对密钥进行加密
			var credentials=new SigningCredentials(key,SecurityAlgorithms.HmacSha256);
			//生成令牌
			var jwtToken = new JwtSecurityToken(
				options.Value.Issuer,//发行人
				options.Value.Audience,//受众
				claims,//荷载
				expires: expires,//设置过期时间
				signingCredentials: credentials);//防伪签名

			var securityToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);//序列化jwt格式

			//生成令牌字符串
			return new TokenResult()
			{
				Access_token = securityToken,
				Expires_in = expires
			};
		}

		/// <summary>
		/// 根据声明 生成token字符串
		/// </summary>
		/// <param name="claims"></param>
		/// <returns></returns>
		public TokenResult CreateToken(List<Claim> claims)
		{
			//生成密钥
			var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("dhajwhdkajwhdkqajwhdkjawhdkjawhdkjawhdjkawhdakjwhdwajkdhjkwh"));
			//设置令牌的过期时间
			DateTime expires = DateTime.Now.AddSeconds(options.Value.Expire);
			//HS256加密 对密钥进行加密
			var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
			var jwtToken = new JwtSecurityToken(
				options.Value.Issuer,        //发布者
				options.Value.Audience,      //受众（发布给谁用）
				claims,                            //发起人 订阅者
				expires: expires,//过期时间
				signingCredentials: credentials);   //秘钥

			var securityToken = new JwtSecurityTokenHandler().WriteToken(jwtToken);//序列化jwt格式

			//生成令牌字符串
			return new TokenResult()
			{
				Access_token = securityToken,
				Expires_in = expires
			};
		}

	}
}
